<template>
  <header class="app-header">
    <div class="header-container">
      <div class="logo" @click="goHome">
        <img src="/vite.svg" alt="Logo" class="logo-img" />
        <span class="logo-text">简单工具集</span>
      </div>
      <nav class="nav-menu">
        <el-menu
          :default-active="activeIndex"
          mode="horizontal"
          router
          :ellipsis="false"
          @select="handleSelect"
        >
          <el-menu-item index="/">首页</el-menu-item>
          <el-menu-item index="/tools">工具</el-menu-item>
          <el-menu-item index="/about">关于</el-menu-item>
        </el-menu>
      </nav>
      <div class="header-actions">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索工具..."
          prefix-icon="Search"
          clearable
          @keyup.enter="handleSearch"
          class="search-input"
        />
      </div>
    </div>
  </header>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()
const searchKeyword = ref('')

// 计算当前激活的菜单项
const activeIndex = computed(() => {
  const path = route.path
  if (path.startsWith('/tool/')) {
    return '/tools'
  }
  return path
})

// 处理菜单选择
const handleSelect = (key: string) => {
  router.push(key)
}

// 处理搜索
const handleSearch = () => {
  if (searchKeyword.value.trim()) {
    router.push({
      path: '/tools',
      query: { keyword: searchKeyword.value }
    })
  }
}

// 返回首页
const goHome = () => {
  router.push('/')
}

// 监听路由变化，更新搜索关键词
watch(() => route.query.keyword, (newKeyword) => {
  if (newKeyword) {
    searchKeyword.value = newKeyword as string
  }
})

onMounted(() => {
  // 初始化搜索关键词
  if (route.query.keyword) {
    searchKeyword.value = route.query.keyword as string
  }
})
</script>

<style scoped>
.app-header {
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 100;
  background-color: white;
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  max-width: 1200px;
  margin: 0 auto;
  height: 60px;
}

.logo {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.logo-img {
  height: 30px;
  margin-right: 10px;
}

.logo-text {
  font-size: 1.5rem;
  font-weight: bold;
  color: #409eff;
}

.nav-menu {
  flex: 1;
  display: flex;
  justify-content: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.search-input {
  width: 200px;
}

@media (max-width: 768px) {
  .header-container {
    flex-wrap: wrap;
    height: auto;
    padding: 10px 20px;
  }
  
  .nav-menu {
    order: 3;
    width: 100%;
    margin-top: 10px;
  }
  
  .search-input {
    width: 150px;
  }
}
</style> 